package com.liushao.controller;


import com.liushao.entity.LendItem;
import com.liushao.entity.vo.InvestVO;
import com.liushao.hfb.RequestHelper;
import com.liushao.result.Result;
import com.liushao.service.LendItemService;
import com.liushao.util.JwtUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 标的出借记录表 前端控制器
 * </p>
 *
 * @author chen
 * @since 2025-01-03
 */
@RestController
@RequestMapping("/api/core/lendItem")
public class LendItemController {

    @Autowired
    private LendItemService lendItemService;

    /*
         .$post('/api/core/lendItem/auth/commitInvest', this.invest)
                .then((response) => {
                  // console.log(response.data.formStr)
                  // debugger
                  document.write(response.data.formStr)
     */
    @ApiOperation("会员投资提交数据")
    @PostMapping("/auth/commitInvest")
    public Result commitInvest(@RequestBody InvestVO investVO, HttpServletRequest request){
        
        String token = null;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies){
            if(cookie.getName().equals("token")){
                token = cookie.getValue();
                break;
            }
        }
        Long userId = JwtUtils.getUserId(token);

        String userName = JwtUtils.getUserName(token);

        investVO.setInvestUserId(userId);
        investVO.setInvestName(userName);

       String formStrs= lendItemService.commitInvest(investVO);

       return Result.ok().data("formStr",formStrs);

    }

    //  http://localhost/api/core/lendItem/notify";
    @PostMapping("/notify")
    public String notifyss(HttpServletRequest request){
        Map<String, Object> objectMap = RequestHelper.switchMap(request.getParameterMap());

        if(RequestHelper.isSignEquals(objectMap)){
              if("0001".equals(objectMap.get("resultCode"))){
                      lendItemService.notifyss(objectMap);
              }else{
                  return  "fail";
              }
        }else{
            System.out.println("回调签名存在问题.....");
            return  "fail";
        }

        return  "success";
    }

    // '/api/core/lendItem/list/' + lendId
    @GetMapping("/list/{lendId}")
    public Result list(
            @ApiParam(value = "标的的id",required = true)
            @PathVariable Long lendId
    ){

        List<LendItem> lendItemList = lendItemService.selectLendById(lendId);

        return  Result.ok().data("list",lendItemList);
    }


}

